import com.mind.jenkins.pipeline.utils.BuildConfig

def call() {
    // properties([
            // parameters([
                    // string(defaultValue: '', description: '', name: 'COMMIT', trim: false),
                    // string(defaultValue: 'pre-release', description: '', name: 'BRANCH', trim: false),
                    // choice(choices: ['EVOFLOW-PRE', 'EVOFLOW-PROD', 'EVOFLOW-DEV'], description: '选择发布环境,默认pre', name: 'ENV'),
                    // choice(choices: ['pre-release', 'release'], description: '选择分支,默认pre-release', name: 'BRANCH'),
            // ])
    // ])

    dockerNode.golangBuildDocker {

        BuildConfig buildConfig
        boolean isSuccess = false
        def causes = currentBuild.getBuildCauses()
        def buildUser = causes[0]?.userId ?: 'Unknown'
        echo "Build User: ${buildUser}"
        try {
            if ("${ENV}" == "EVOFLOW-PROD"){
                stage('部署生产之前二次确认') {
                    input(message: "确定发布环境 ${ENV} 的 ${BRANCH}分支？", ok: 'Continue')
                }
            }
            stage('准备拉取代码') {
                //checkout scm
                checkout([
                        $class           : 'GitSCM',
                        branches         : [[name: BRANCH]],
                        userRemoteConfigs: scm.userRemoteConfigs
                ])
            }

            

            echo "当前发布环境：${ENV}, 当前发布分支：${BRANCH}"

            String appname = jobUtil.getAppNameFromJob()
            echo "当前服务名：${appname}"

            Object commitInfo = jobUtil.getCommitInfo()

            String imageAddr = jobUtil.getImageAdd(ENV)

            String imageName
            String coskey
            if (params.golangVersion == null){
                goVersion = "golang-v1.17"
            }else{
                goVersion = params.golangVersion
            }

            stage('构建镜像') {        
                parallel 'docker': {
                    echo "Build docker image..."
                    def root = tool name: "${goVersion}", type: 'go'        
                    withEnv(["GOROOT=${root}", "PATH+GO=${root}/bin"]){
                        // sh 'export GOPRIVATE=mind-git.im30.lan'
                        // sh 'export GOINSECURE=mind-git.im30.lan'
                        // sh 'go env -w GO111MODULE=on'
                        // sh 'go env -w GOPROXY=https://goproxy.cn,direct'
                        // sh 'go env -w CGO_ENABLED=0'
                        // sh 'go env'
                        // sh 'go mod tidy'
                        // sh 'go build -o server .'
                        sh 'make'
                        archiveArtifacts artifacts: '*server', allowEmptyArchive: true
                        imageName = "${imageAddr}/${appname}:${commitInfo.version}"
                        sh(script: "sed -i '/go build ./i \\\\    && go vet ./... \\\\' ./Dockerfile")
                        dockerfile = "./Dockerfile"
                        currentBuild.description = "发布环境: ${ENV} \n分支名称: ${BRANCH} \n发布用户: ${buildUser} \n镜像版本号: ${commitInfo.version}"
                        jobUtil.buildDockerImage(dockerfile, "", "golang", imageName,"")
                    }
                   
                    
                }, 'cos': {
                     echo "构建文件上传COS中..."
                }
            }

            stage('单元测试') {
                echo "单元测试中...."
            }

            stage('质量检测') {
                echo "SonarScanner质量检查扫描中...."
            }

            stage('应用部署') {
                echo "Build success, Now Callback Cd..."
                String env = params.ENV
                if ( appname == "mind-job-server" ){
                    jobUtil.createBananaBuild(appname, "sts", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else if (appname == "mind-sync-server" ){
                    jobUtil.createBananaBuild(appname, "cron", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }else{
                    jobUtil.createBananaBuild(appname, "deploy", env, buildUser, coskey, imageName, commitInfo, params.BRANCH)
                }
                
            }
        } finally {
            try {
                stage('通知') {
                    echo "通知工作群..."
                    isSuccess = currentBuild.result == null || currentBuild.result == 'SUCCESS'
                    String branch = params.BRANCH
                    String env = params.ENV
                    notifyUtil.notifyApp(jobUtil.getRepoName(), branch, env, isSuccess, buildUser)
                }
                
            } catch (err) {
                echo err.getMessage()
            }
            // deleteDir()
        }
    }
}